package com.example.springmvcdemo;

import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;

@RestController
@RequestMapping("/controller")
public class RequestController {
    @RequestMapping("/setsession")
    public String setSession(HttpServletRequest httpServletRequest) {
        HttpSession session = httpServletRequest.getSession(true);
        session.setAttribute("username", "zhangsan");
        return "username: zhangsan";
    }
    @RequestMapping("/getcookie")
    public String getCookie(HttpServletRequest httpServletRequest) {
        Cookie[] cookies = httpServletRequest.getCookies();
        StringBuilder sb =new StringBuilder();
        for (Cookie cookie : cookies) {
            sb.append(cookie.getName());
            sb.append(": ");
            sb.append(cookie.getValue());
        }

        return sb.toString();
    }

    @RequestMapping("/getcookie1")
    public String getCookie1(@CookieValue("bite") String bite) {
        return "bite" + bite;
    }

    @RequestMapping("/getsession")
    public String getSession(HttpServletRequest httpServletRequest) {
        HttpSession httpSession = httpServletRequest.getSession(false);
        if (httpSession != null) {
            String username = (String)httpSession.getAttribute("username");
            return username;
        }
        return null;
    }

    @RequestMapping("/getsession1")
    public String getSession1(HttpSession httpSession) {
        if (httpSession != null) {
            return (String)httpSession.getAttribute("username");
        }

        return null;
    }
}
